﻿package com.secneo.appshare.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.ActivityGroup;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.ActivityUtil;
import com.secneo.appshare.common.AppSharePreference;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.MD5;
import com.secneo.appshare.common.Update;
import com.secneo.appshare.common.Util;
import com.secneo.appshare.database.AppFile;
import com.secneo.appshare.database.AppMdSha;
import com.secneo.appshare.database.AppShareDatabaseHelper;
import com.secneo.mp.MpApi;
import com.secneo.mp.api.database.DatabaseHelper;

public class MainActivity extends ActivityGroup
{
	public static final int HELP = Menu.FIRST;
	public static final int INEDX = Menu.FIRST + 1;
	public static final int LOGINOUT = Menu.FIRST + 4;
	public static final int MEMBER_SETTING = Menu.FIRST + 5;
	public static final int MEMBER_SYNCHRONIZATION= Menu.FIRST + 6;
	public static final int MEMBER_FIRENDS = Menu.FIRST + 7;
	private final static String FIRST_CONFIG_MESSAGE = "first_config_message";
	private final static String CHANNEL_ID = "channel_id";
	private Button mTopbarRight, mMySpaceButton;
	private TextView mTopbarTxt;
	private LinearLayout mContainerLinear;
	private RadioGroup mRadioGroup;
	private RadioButton mLogsButton,mAppsButton,mSquareButton,mTopListButton;
	private Thread sendApp = null;
	private Thread sendMd5App=null;
	private int closeSelfFlag=0;
	public enum ActivityIndex
	{
		LogsActivity,
		AppsActivity,
		SquareActivity,
		TopListActivity,
	}
	private ActivityIndex mCurrentActivity;
	private Handler mMainHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			switch(msg.what) 
			{
			
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appshare_main);
		AppShareApplication.getInstance().addActivity(this);
		Thread updateThread = new Thread()
		{
			public void run()
			{
				try
				{
					MpApi mp = MpApi.getAPI();
					SharedPreferences saving = getSharedPreferences(FIRST_CONFIG_MESSAGE, 0);
					Update.checkVersion(MainActivity.this, MainActivity.this, mMainHandler, Constants.PACKAGENAME, Constants.VERSION_CODE, "1", 0, 
										mp.getPhoneMd5Imei(MainActivity.this), saving.getString(CHANNEL_ID, ""));

				} catch (Exception ex)
				{
					ex.printStackTrace();
				}
			}
		};
		updateThread.start();
		
		mTopbarRight = (Button) findViewById(R.id.img_search);
		mTopbarRight.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				if(!AppSharePreference.isAppShareUserLogined(MainActivity.this))
				{
					Intent intent=new Intent();
					intent.setClass(MainActivity.this, LoginChooseMethodActivity.class);
					startActivity(intent);
				}else
				{
					DatabaseHelper dh=new DatabaseHelper(MainActivity.this);
					dh.insertUserAppPopularityBycatagory(MainActivity.this,2013);
					dh.close();
				Intent intent=new Intent();
				intent.setClass(MainActivity.this, SearchActivity.class);
				MainActivity.this.startActivity(intent);
				}
			}
		});
		mMySpaceButton = (Button) findViewById(R.id.btn_mySpace);
		mMySpaceButton.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				if(!AppSharePreference.isAppShareUserLogined(MainActivity.this))
				{
					Intent intent=new Intent();
					intent.setClass(MainActivity.this, LoginChooseMethodActivity.class);
					startActivity(intent);
				}else
				{
					DatabaseHelper dh=new DatabaseHelper(MainActivity.this);
					dh.insertUserAppPopularityBycatagory(MainActivity.this,2001);
					dh.close();
					Intent intent=new Intent();
					intent.setClass(MainActivity.this, UserAppActivity.class);
					MainActivity.this.startActivity(intent);
				}
			}
		});
		mTopbarTxt = (TextView) findViewById(R.id.topbar_txt);
		mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
		mRadioGroup.setOnCheckedChangeListener(mRadioGroupListener);
		mLogsButton = (RadioButton) findViewById(R.id.toggle_logs);
		mAppsButton = (RadioButton) findViewById(R.id.toggle_apps);
		mSquareButton = (RadioButton) findViewById(R.id.toggle_square);
		mTopListButton = (RadioButton) findViewById(R.id.toggle_toplist);
		mContainerLinear = (LinearLayout) findViewById(R.id.mainLinear);
		int actitvityIndex = getIntent().getIntExtra(Constants.MAINACTIVITYINDEXACTION,-1) ;
		startChildActivty(actitvityIndex) ;
		
		creatSendThreads();
		String uid = LocalStore.getLocaleStoreInstance(this).getUid();
		if (!uid.equals("")) 
		{
			sendApp.start();
		    sendMd5App.start();
		}
	}
	
	@Override
	protected void onNewIntent(Intent intent) 
	{
		super.onNewIntent(intent);
		int actitvityIndex = intent.getIntExtra(Constants.MAINACTIVITYINDEXACTION,-1) ;
		startChildActivty(actitvityIndex) ;
	}

	private void startChildActivty(int actitvityIndex)
	{		
		if(actitvityIndex != -1)
		{
			switch(actitvityIndex)
			{
				case 0:
					mLogsButton.performClick();
					break ;
				case 1:
					mAppsButton.performClick();
					break ;
				case 2:
					mSquareButton.performClick();
					break ;
				case 3:
					mTopListButton.performClick();
					break ;
			}
		} else 
			mLogsButton.performClick();
	}
	
	private RadioGroup.OnCheckedChangeListener mRadioGroupListener = new RadioGroup.OnCheckedChangeListener()
	{
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId)
		{
			setRecyleFlag();
			Util.logHeap(MainActivity.this.getClass());
			if (checkedId == mLogsButton.getId())
			{
				mCurrentActivity = ActivityIndex.LogsActivity;
				mTopbarTxt.setText("分享动态");
				mContainerLinear.removeAllViews();
				mContainerLinear.addView(MainActivity.this.getLocalActivityManager().startActivity(
                        "Logs",
                       new Intent(MainActivity.this, MainLogsActivity.class)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        .putExtra("FromGroup", true))
                        .getDecorView(), LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

			} 
			else if (checkedId == mAppsButton.getId())
			{
				mCurrentActivity = ActivityIndex.AppsActivity;
				mTopbarTxt.setText("游戏");
				mContainerLinear.removeAllViews();
				mContainerLinear.addView(MainActivity.this.getLocalActivityManager().startActivity(
                        "Apps",
                        new Intent(MainActivity.this, MainAppsActivity.class)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        .putExtra("FromGroup", true))
                        .getDecorView(), LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			}
			else if (checkedId == mSquareButton.getId())
			{
				mCurrentActivity = ActivityIndex.SquareActivity;
				mTopbarTxt.setText("广场");
				mContainerLinear.removeAllViews();
				mContainerLinear.addView(MainActivity.this.getLocalActivityManager().startActivity(
                        "Square",
                        new Intent(MainActivity.this, MainSquareActivity.class)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        .putExtra("FromGroup", true))
                        .getDecorView(), LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			}
			else if (checkedId == mTopListButton.getId())
			{
				mCurrentActivity = ActivityIndex.TopListActivity;
				mTopbarTxt.setText("排行榜");
				mContainerLinear.removeAllViews();
				mContainerLinear.addView(MainActivity.this.getLocalActivityManager().startActivity(
                        "TopList",
                        new Intent(MainActivity.this, MainTopListActivity.class)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                        .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        .putExtra("FromGroup", true))
                        .getDecorView(), LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			}
		}
	};

	private void setRecyleFlag()
	{
		MainLogsActivity.mRecyleFlag = false;
		MainAppsActivity.mRecyleFlag = false;
		MainSquareActivity.mRecyleFlag = false;
		MainTopListActivity.mRecyleFlag = false;
		if(mCurrentActivity ==  ActivityIndex.LogsActivity)
			MainLogsActivity.mRecyleFlag = true;
		else if(mCurrentActivity ==  ActivityIndex.AppsActivity)
			MainAppsActivity.mRecyleFlag = true;
		else if(mCurrentActivity ==  ActivityIndex.SquareActivity)
			MainSquareActivity.mRecyleFlag = true;
		else if(mCurrentActivity ==  ActivityIndex.TopListActivity)
			MainTopListActivity.mRecyleFlag = true;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		String help = this.getResources().getString(R.string.menu_help);
		String loginout = this.getResources().getString(R.string.menu_logout);
		String memberSetting = this.getResources().getString(R.string.menu_member_setting);
		String synchronization = this.getResources().getString(R.string.menu_synchronization);
		String firends = this.getResources().getString(R.string.menu_firends);
		
		menu.add(0, MEMBER_SYNCHRONIZATION, 2, synchronization).setIcon(R.drawable.menu_synchronization);
		menu.add(0, MEMBER_SETTING, 3, memberSetting).setIcon(R.drawable.menu_setting);
		menu.add(0, HELP, 4, help).setIcon(R.drawable.menu_help);
		menu.add(0, MEMBER_FIRENDS, 5, firends).setIcon(R.drawable.menu_firends);
		menu.add(0, LOGINOUT, 6, loginout).setIcon(R.drawable.menu_loginout);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		Intent intent = new Intent();
		switch (item.getItemId())
		{
			case HELP:
				HelpWebViewActivity2.go(this, Constants.URL_HELP, getString(R.string.menu_help));
				return true;

			case LOGINOUT:
				ActivityUtil.closeSelfApp(MainActivity.this);
				return true;
				
			case MEMBER_SETTING:
				if (!AppSharePreference.isAppShareUserLogined(MainActivity.this))
				{
					intent.setClass(this, LoginChooseMethodActivity.class);
					startActivity(intent);
				} else
				{
					intent.setClass(this, MemberSettingActivity.class);
					startActivity(intent);
				}
				return true;

			case MEMBER_SYNCHRONIZATION:
				DatabaseHelper dh = new DatabaseHelper(MainActivity.this);
				dh.insertUserAppPopularityBycatagory(MainActivity.this, 2029);
				dh.close();
				if (!AppSharePreference.isAppShareUserLogined(MainActivity.this))
				{
					intent.setClass(this, LoginChooseMethodActivity.class);
					startActivity(intent);
				} else
				{
					intent.setClass(this, AccountManagementActivity.class);
					startActivity(intent);
				}

				return true;

			case MEMBER_FIRENDS:
				DatabaseHelper dh1 = new DatabaseHelper(MainActivity.this);
				dh1.insertUserAppPopularityBycatagory(MainActivity.this, 2030);
				dh1.close();
				ActivityUtil.userShare(this, this.getResources().getString(R.string.share_content), 2);
				return true;
			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		closeSelfFlag=0;
		
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		closeSelfFlag=0;
		
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) 
	{
		if (keyCode == KeyEvent.KEYCODE_BACK) 
		{
			closeSelfFlag=closeSelfFlag+1;
			if(closeSelfFlag==1)
			{
				Toast.makeText(this, this.getResources().getString(R.string.toast_close_self), Toast.LENGTH_SHORT).show();
			}else if(closeSelfFlag==2)
			{
				ActivityUtil.closeSelfApp(MainActivity.this);
			}
		
			return true;
		} 
		else 
			return super.onKeyDown(keyCode, event);
	}
	
	public void creatSendThreads()
	{
		sendApp = new Thread()
		{
			public void run()
			{
				try
				{
					boolean addFlag = false;
					Log.d("MyTag", "AppallStatus=" + AppSharePreference.isAppallStatus(MainActivity.this));
					if (!AppSharePreference.isAppallStatus(MainActivity.this))
					{
						Log.d("MyTag", "Appall isAppallStatus=" + AppSharePreference.isAppallStatus(MainActivity.this));
						AppShareDatabaseHelper adh = new AppShareDatabaseHelper(MainActivity.this);
						adh.getAppFileByPackageName(adh, Constants.PACKAGENAME);
						adh.cleanAppFileTable();
						adh.close();
					}

					RemoteApiImpl remoteApi = new RemoteApiImpl();
					final PackageManager pm = getPackageManager();
					List<ApplicationInfo> allApps = pm.getInstalledApplications(0);
					final List<ApplicationInfo> filteredApps = Util.filterUserApps(allApps);
					AppShareDatabaseHelper asdh = new AppShareDatabaseHelper(MainActivity.this);
					ArrayList<AppFile> appFileList = asdh.getAppFiles(asdh);
					Log.d("MyTag", "appFileList1=" + appFileList.size());
					// add new app
					for (int i = 0; i < filteredApps.size(); i++)
					{
						ApplicationInfo appInfo = filteredApps.get(i);
						for (int j = 0; j < appFileList.size(); j++)
						{
							addFlag = false;
							AppFile appFile = appFileList.get(j);
							if (appInfo.packageName.equals(appFile.getPackageName()))
							{
								addFlag = true;
								break;
							}
						}
						if (!addFlag)
						{
							PackageInfo info = pm.getPackageInfo(appInfo.packageName, 0);// this.getPackageName()这个是程序包名
							String appName = info.applicationInfo.loadLabel(getPackageManager()).toString();
							AppFile appFile = new AppFile();
							appFile.setPackageName(appInfo.packageName);
							appFile.setName(appName);
							long hh = asdh.insertAppFile(appFile);
						}
					}

					// delete old app
					for (int i = 0; i < appFileList.size(); i++)
					{
						AppFile appFile = appFileList.get(i);

						for (int j = 0; j < filteredApps.size(); j++)
						{
							addFlag = false;
							ApplicationInfo appInfo = filteredApps.get(j);
							if (appInfo.packageName.equals(appFile.getPackageName()))
							{
								addFlag = true;
								break;
							}
						}
						if (!addFlag)
						{
							appFile.setUninst(1);
							asdh.updateAppFile(appFile);
						}
					}

					String uid = LocalStore.getLocaleStoreInstance(MainActivity.this).getUid();
					AppShareDatabaseHelper asdh2 = new AppShareDatabaseHelper(MainActivity.this);
					ArrayList<AppFile> appListUninst = asdh2.getAppFileByUninst(asdh2);
					ArrayList<AppFile> appListForSend = asdh2.getAppFile(asdh2);
					Log.d("MyTag", "appListForSend=" + appListForSend.size());
					if (AppSharePreference.isAppallStatus(MainActivity.this))
					{
						if (appListForSend.size() != 0)
						{
							String status1 = remoteApi.getAppFile(MainActivity.this, uid, 2, appListForSend);
							if (status1 != null && !"".equals(status1))
							{

								for (int j = 0; j < appListForSend.size(); j++)
								{
									AppFile appFile = appListForSend.get(j);
									AppFile appFiles = asdh2.getAppFileByPackageName(asdh2, appFile.getPackageName());
									appFiles.setUpdateServer(1);
									asdh2.updateAppFile(appFiles);
								}
							}
						}

						if (appListUninst.size() != 0)
						{
							String status = remoteApi.getAppFile(MainActivity.this, uid, 3, appListUninst);
							if (status != null && !"ok".equals(status))
							{
								for (int i = 0; i < appListUninst.size(); i++)
								{
									AppFile appFile = appListUninst.get(i);
									asdh.deleteAppFile(appFile.getPackageName());
								}
							}

						}
					} else
					{
						String status1 = remoteApi.getAppFile(MainActivity.this, uid, 1, appListForSend);
						Log.d("MyTag", "appList status1=" + status1);
						if (status1 != null && "ok".equals(status1))
						{
							for (int j = 0; j < appListForSend.size(); j++)
							{
								AppFile appFile = appListForSend.get(j);
								AppFile appFiles = asdh2.getAppFileByPackageName(asdh2, appFile.getPackageName());
								appFiles.setUpdateServer(1);
								asdh2.updateAppFile(appFiles);
							}
							AppSharePreference.setAppallStatus(MainActivity.this, true);
						}
					}

				} catch (Exception ex)
				{
					ex.printStackTrace();
				}
			}
		};

		sendMd5App = new Thread()
		{
			public void run()
			{
				try
				{
					String uid = LocalStore.getLocaleStoreInstance(MainActivity.this).getUid();
					RemoteApiImpl remoteApi = new RemoteApiImpl();
					boolean addFlag = false;
					PackageManager pm = getPackageManager();
					List<ApplicationInfo> allApps = pm.getInstalledApplications(0);
					List<ApplicationInfo> filteredApps = Util.filterUserApps(allApps);
					AppShareDatabaseHelper asdh = new AppShareDatabaseHelper(MainActivity.this);
					ArrayList<AppMdSha> appFileList = asdh.getAppMdShas(asdh);
					Log.d("MyTag", "sendMd5AppappFileList=" + appFileList.size());
					// add new app
					for (int i = 0; i < filteredApps.size(); i++)
					{
						ApplicationInfo appInfo = filteredApps.get(i);
						for (int j = 0; j < appFileList.size(); j++)
						{
							addFlag = false;
							AppMdSha appMdSha = appFileList.get(j);
							if (appInfo.packageName.equals(appMdSha.getPackageName()))
							{
								addFlag = true;
								break;
							}
						}
						if (!addFlag)
						{
							AppMdSha appMdSha = new AppMdSha();
							appMdSha.setPackageName(appInfo.packageName);
							PackageInfo packageInfo = pm.getPackageInfo(appInfo.packageName, 0);
							appMdSha.setVersion(packageInfo.versionName);
							appMdSha.setAppMd5(MD5.getmd5ByAPK(appInfo.publicSourceDir, "MD5"));
							appMdSha.setAppSha(MD5.getmd5ByAPK(appInfo.publicSourceDir, "SHA-256"));
							appMdSha.setMemo("0");
							appMdSha.setStatus(0);
							asdh.insertAppMd5Sha(appMdSha);
						}
					}

					AppShareDatabaseHelper asdh1 = new AppShareDatabaseHelper(MainActivity.this);
					if (!AppSharePreference.isAppMdShaStatus(MainActivity.this))
					{
						ArrayList<AppMdSha> appFileList1 = asdh1.getAppMdSha(asdh1);
						String status1 = remoteApi.getAppMdSha(MainActivity.this, uid, appFileList1);
						if (status1 != null && !"".equals(status1))
						{
							for (int i = 0; i < appFileList1.size(); i++)
							{
								AppMdSha am = appFileList1.get(i);
								am.setUpdateServer(1);
							}
							AppSharePreference.setAppMdShaStatus(MainActivity.this, true);
						}
					} else
					{
						ArrayList<AppMdSha> appFileList1 = asdh1.getAppMdSha(asdh1);
						ArrayList<AppMdSha> appFileList2 = asdh.getAppMdShas(asdh1);
						Log.d("MyTag", "appFileList md5=" + appFileList.size());
						// add new app
						for (int i = 0; i < filteredApps.size(); i++)
						{
							ApplicationInfo appInfos = filteredApps.get(i);
							for (int j = 0; j < appFileList2.size(); j++)
							{
								AppMdSha appMdSha = appFileList2.get(j);
								String appInfoMd5 = appInfos.publicSourceDir;
								if (!MD5.getmd5ByAPK(appInfoMd5, "MD5").equals(appMdSha.getAppMd5()))
								{
									appMdSha.setAppMd5(MD5.getmd5ByAPK(appInfoMd5, "MD5"));
									appMdSha.setAppSha(MD5.getmd5ByAPK(appInfos.publicSourceDir, "SHA-256"));
									appFileList1.add(appMdSha);
								}
							}
						}
						String status1 = remoteApi.getAppMdSha(MainActivity.this, uid, appFileList1);
						if (status1 != null && !"".equals(status1))
						{
							for (int i = 0; i < appFileList1.size(); i++)
							{
								AppMdSha am = appFileList1.get(i);
								am.setUpdateServer(1);
							}
						}
					}

				} catch (Exception ex)
				{
					ex.printStackTrace();
				}
			}
		};
	}
}
